//
//  ExerTypeChooseVc.m
//   CareRing
//
//  Created   on 2023/10/18.
//

#import "WorkoutVc.h"
#import <Masonry/Masonry.h>
#import "ConfigModel.h"
#import "SelectItem.h"
#import "CAnAlgExerData+Desc.h"
#import "Colors.h"
#import "CARingSDK.h"
#import "CABLeService.h"
#import "FunctionButton.h"
#import "CARingSDK+Desc.h"
#import "CADeviceInfo+description.h"
extern const CGFloat EXEC_ITEM_HEIGHT;
@interface WorkoutVc ()<CABleScanProtocal, CABleDataProtocal>

@property(strong, nonatomic)NSMutableArray<NSNumber *> *typeArray;

@property(strong, nonatomic)NSMutableArray<SelectItem *> *workOutItemArray;
@property(strong, nonatomic)UIScrollView *scrollView;
@property(strong, nonatomic)UIView *itemContent, *bottomContent;

@property(weak, nonatomic)UITextField *duraTf;
@property(assign, nonatomic)NALG_EXERCISE_TYPE workoutType;

@property(strong, nonatomic)FunctionButton *startWkBtn, *endWkBtn, *restoreWkBtn, *pauseWkBtn;
@property(strong, nonatomic)FunctionButton *rltDataRepOnBtn, *rltDataRepOffBtn;
@property(strong, nonatomic)UISegmentedControl *segPoolsize;
@end

@implementation WorkoutVc

- (void)viewDidLoad {
    [super viewDidLoad];
    WEAK_SELF
    [self customNavStyleNormal:_L2(L_TX_WORKOUT) BackBlk:^{
        STRONG_SELF
        [strongSelf.navigationController popViewControllerAnimated:YES];
    }];
    [self initData];
   
    
    [self initUI];
    
    self.segPoolsize.enabled = NO;
}

-(void)initData {
  
    self.typeArray = [NSMutableArray new];
    


    [self.typeArray addObjectsFromArray:@[  @(    NALG_EXERCISE_RUN),// 室外跑步
                                            @(    NALG_EXERCISE_POOL_SWIMING),
                                            @(    NALG_EXERCISE_WALK),  // 步行
                                            @(    NALG_EXERCISE_OUTDOOR_CYCLING),
                                            @(    NALG_EXERCISE_INDOOR_CYCLING),
                                            @(    NALG_EXERCISE_YOGA),
                                            @(    NALG_EXERCISE_MINDFUL),
                                        ]];
    /*
   
     */
    
    for (NSNumber *type in self.existTypeArray) { // 去除外部已存在的选项
        for (NSNumber *showType in self.typeArray) {
            if (type.intValue == showType.intValue) {
                [self.typeArray removeObject:showType];
                break;
            }
        }
        
    }
    
    self.workOutItemArray = [NSMutableArray new];
    
    for (NSNumber *type in self.typeArray) {
        
        SelectItem *runItem = [[SelectItem alloc]initWithStyle:NORMAL_STYLE];
        [runItem addBottomSepLine:SEPLINE_COLOR(0.3) Width:0.3];
        runItem.data = type; // 标记类型
        [runItem setLeftText:[CAnAlgExerData workoutTypeDesc:type.integerValue]];
        runItem.itemColorManager.selectedTxtColor = MAIN_BLUE;
        runItem.itemColorManager.unselecTxtColor = UIColor.whiteColor;
        runItem.itemColorManager.selectedBgColor = UIColor.clearColor;
        runItem.itemColorManager.unselecBgColor = UIColor.clearColor;
        WEAK_SELF
        runItem.clickBLK = ^(SelectItem * _Nonnull view) {
            STRONG_SELF
            [strongSelf workoutCLick:view];
        };
        
        
        [self.workOutItemArray addObject:runItem];

    }
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, CGRectGetMaxY(self.bottomContent.frame));
}

-(void)workoutCLick:(SelectItem *)item {
    
    item.selected = YES;
    for (SelectItem *v in self.workOutItemArray) {
        if (v != item) {
            v.selected = !item.selected;
        }
    }
    self.workoutType = [item.data unsignedIntValue];
    
    self.segPoolsize.enabled = self.workoutType ==     NALG_EXERCISE_POOL_SWIMING;

}



-(void)initUI {

    
    [self.view addSubview:self.scrollView];
    self.itemContent = [UIView new];
    [self.scrollView addSubview:self.itemContent];
    
    UILabel *durationLbl = [UILabel new];
    durationLbl.text = _L2(L_TX_WK_EXPLAIN);
    [self.scrollView addSubview:durationLbl];

    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view.mas_leading).offset(VC_ITEM_MARGIN_HOR);
        make.trailing.equalTo(self.view.mas_trailing).inset(VC_ITEM_MARGIN_HOR);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];
    
    UITextField *duraTf = [[UITextField alloc]init];
    duraTf.keyboardType = UIKeyboardTypeNumberPad;
    duraTf.borderStyle = UITextBorderStyleRoundedRect;
    [self.scrollView addSubview:duraTf];
    self.duraTf = duraTf;
    self.duraTf.placeholder = _L2(L_TX_WK_EXPLAIN);
    
    [durationLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(durationLbl.superview.mas_top).offset(20);
        make.height.equalTo(@30);
        make.leading.equalTo(durationLbl.superview).offset(VC_ITEM_MARGIN_HOR);
        
    }];
    [self.duraTf mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(durationLbl.mas_bottom);
        make.leading.equalTo(self.duraTf.superview.mas_leading).offset(VC_ITEM_MARGIN_HOR);
        make.trailing.equalTo(self.duraTf.superview.mas_trailing).inset(VC_ITEM_MARGIN_HOR);
        make.height.equalTo(@35);
    }];
        
    UILabel *workoutNamesLbl = [UILabel new];
    [self.scrollView addSubview:workoutNamesLbl];
    workoutNamesLbl.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:18];
    workoutNamesLbl.text = _L2(L_SUPPORT_EXER_TYPES);
    [workoutNamesLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.duraTf.mas_bottom).offset(20);
        make.height.equalTo(@30);
        make.leading.trailing.equalTo(self.itemContent);
    }];

    [self layoutTop:self.itemContent];
    

    
    [self.itemContent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.itemContent.superview.mas_centerX);
        make.top.equalTo(workoutNamesLbl.mas_bottom).offset(5);
        make.leading.equalTo(self.itemContent.superview.mas_leading).offset(VC_ITEM_MARGIN_HOR);
        make.trailing.equalTo(self.itemContent.superview.mas_trailing).inset(VC_ITEM_MARGIN_HOR);

    }];
    
    self.bottomContent = [UIView new];
    
    [self.scrollView addSubview:self.bottomContent];
    [self.bottomContent mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.bottomContent.superview.mas_centerX);
        make.top.equalTo(self.itemContent.mas_bottom).offset(5);
        make.leading.trailing.equalTo(self.itemContent);
        
    }];
    
    [self layoutBottom:self.bottomContent];
    [self.scrollView setNeedsLayout];
    [self.view layoutIfNeeded];
    
}



-(void)layoutTop:(UIView *)cnt {
    
    cnt.layer.cornerRadius = ITEM_CORNOR_RADIUS;
    cnt.layer.masksToBounds = YES;
    cnt.backgroundColor = SLEEP_READY_XLABEL_HEAD_TAIL_BG_COLOR;
    
  
    
    for (int i = 0; i < self.workOutItemArray.count; i++) {
        [cnt addSubview:self.workOutItemArray[i]];
    }
    for (int i = 0; i < self.workOutItemArray.count; i++) {
        SelectItem *v = self.workOutItemArray[i];
        [v mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(v.superview);
            if (i == 0) {
                make.top.equalTo(v.superview.mas_top);
            }
            if (i == self.workOutItemArray.count-1) {
                make.bottom.equalTo(v.superview.mas_bottom);
            }
            if (i > 0 && self.workOutItemArray.count > 1) {
                make.top.equalTo(self.workOutItemArray[i-1].mas_bottom);
            }
            make.height.equalTo(@(EXEC_ITEM_HEIGHT));

        }];
    }

}

-(void)layoutBottom:(UIView *)cnt
{
    UILabel *wkPoolsezeLbl = [UILabel new];
    wkPoolsezeLbl.text = _L2(L_TX_POOL_SIZE);
    [cnt addSubview:wkPoolsezeLbl];
    [wkPoolsezeLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.equalTo(wkPoolsezeLbl.superview);
        make.height.equalTo(@30);
    }];
    
    self.segPoolsize = [[UISegmentedControl alloc]initWithItems:@[@"Unknow", @"25 m", @"50 m"]];
    [cnt addSubview:self.segPoolsize];
    [self.segPoolsize mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wkPoolsezeLbl.mas_bottom).offset(5);
        make.leading.equalTo(wkPoolsezeLbl);
        make.height.equalTo(@30);
        make.width.equalTo(@200);
    }];
    self.segPoolsize.selectedSegmentIndex = 1;
    
    
    UILabel *wkStaLbl = [UILabel new];
    wkStaLbl.text = _L2(L_WK_STATUS);
    [cnt addSubview:wkStaLbl];
    [wkStaLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(wkStaLbl.superview);
        make.top.equalTo(self.segPoolsize.mas_bottom).offset(5);
        make.height.equalTo(@30);
    }];
    // start end
    [cnt addSubview:self.startWkBtn];
    [cnt addSubview:self.endWkBtn];

    [self.startWkBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(cnt);
        make.top.equalTo(wkStaLbl.mas_bottom);
        make.height.equalTo(@40);
    }];
    [self.endWkBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(cnt);
        make.top.equalTo(self.startWkBtn.mas_top);
        make.width.height.equalTo(self.startWkBtn);
        make.leading.equalTo(self.startWkBtn.mas_trailing).offset(15);
    }];
    
    // restore pause
    [cnt addSubview:self.restoreWkBtn];
    [cnt addSubview:self.pauseWkBtn];

    [self.restoreWkBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(self.startWkBtn);
        make.top.equalTo(self.startWkBtn.mas_bottom).offset(10);
    }];
    [self.pauseWkBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(self.endWkBtn);
        make.top.equalTo(self.restoreWkBtn.mas_top);

    }];
    
    UILabel *wkrltDataLbl = [UILabel new];
    wkrltDataLbl.text = _L2(L_WK_RLTDATA_REP);
    [cnt addSubview:wkrltDataLbl];
    [wkrltDataLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.height.equalTo(wkStaLbl);
        make.top.equalTo(self.restoreWkBtn.mas_bottom).offset(15);
    }];
    
    [cnt addSubview:self.rltDataRepOnBtn];
    [cnt addSubview:self.rltDataRepOffBtn];
    
    [self.rltDataRepOnBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(self.startWkBtn);
        make.bottom.equalTo(cnt.mas_bottom).inset(20);
        make.top.equalTo(wkrltDataLbl.mas_bottom).offset(10);

    }];
    [self.rltDataRepOffBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(self.endWkBtn);
        make.top.equalTo(self.rltDataRepOnBtn.mas_top);

    }];

    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    CARingSDK.instance.blescanDelegate = self;
    CARingSDK.instance.bleDataDelegate = self;

}




-(UIScrollView *)scrollView
{
    if(!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}



-(FunctionButton *)startWkBtn
{
    if (!_startWkBtn) {
        _startWkBtn = [FunctionButton functionButton:_L2(L_START)];
        WEAK_SELF
        [_startWkBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (!CARingSDK.instance.currentDevice.isConnected) {
                return;
            }
            
            if (strongSelf.workoutType == 0) {
                [strongSelf showAlertWarningWithTitle:@"Tips" Msg:@"Please select the type of workout first." btnCancel:_L2(L_OK) Compelete:nil];
                return;
            }
            
            CA_NALG_SWIM_POOL_SIZE poolsize = strongSelf.segPoolsize.selectedSegmentIndex;
            
            int duration = [strongSelf.duraTf.text intValue];
            
            [CARingSDK.instance functionStartNalgExerciseWithType:strongSelf.workoutType PoolSize:poolsize DurationMins:(uint16_t)duration];
            
        }];
    }
    return _startWkBtn;
}
-(FunctionButton *)endWkBtn
{
    if (!_endWkBtn) {
        _endWkBtn = [FunctionButton functionButton:_L2(L_END)];
        [_endWkBtn setTitleColor:BUTTON_RED forState:UIControlStateNormal];
        WEAK_SELF
        [_endWkBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {
                [CARingSDK.instance functionStopNalgExercise]; //停止锻炼
            }
        }];
    }
    return _endWkBtn;
}
-(FunctionButton *)restoreWkBtn
{
    if (!_restoreWkBtn) {
        _restoreWkBtn = [FunctionButton functionButton:_L2(L_RESTORE)];
        WEAK_SELF
        [_restoreWkBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {

                [CARingSDK.instance functionContinueNalgExercise];
            }
        }];
    }
    return _restoreWkBtn;
}
-(FunctionButton *)pauseWkBtn
{
    if (!_pauseWkBtn) {
        _pauseWkBtn = [FunctionButton functionButton:_L2(L_PAUSE)];
        [_pauseWkBtn setTitleColor:BUTTON_RED forState:UIControlStateNormal];
        WEAK_SELF
        [_pauseWkBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {

                [CARingSDK.instance functionPauseNalgExercise];
            }
        }];
    }
    return _pauseWkBtn;
}

-(FunctionButton *)rltDataRepOnBtn
{
    if (!_rltDataRepOnBtn) {
        _rltDataRepOnBtn = [FunctionButton functionButton:@"On"];
        WEAK_SELF
        [_rltDataRepOnBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {
                [CARingSDK.instance functionNalgRealtimeReportDurinExerciseSwitch:YES];
            }

        }];
    }
    return _rltDataRepOnBtn;
}
-(FunctionButton *)rltDataRepOffBtn
{
    if (!_rltDataRepOffBtn) {
        _rltDataRepOffBtn = [FunctionButton functionButton:@"Off"];
        [_rltDataRepOffBtn setTitleColor:BUTTON_RED forState:UIControlStateNormal];

        WEAK_SELF
        [_rltDataRepOffBtn addTapBlk:^(FunctionButton * _Nonnull btn) {
            STRONG_SELF
            if (CARingSDK.instance.currentDevice.isConnected) {
                [CARingSDK.instance functionNalgRealtimeReportDurinExerciseSwitch:NO];
            }
        }];
    }
    return _rltDataRepOffBtn;
}

- (void)caBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CA_CMD_EXECTE_ERROR_REASON)reason Data:(nonnull NSData *)originData { 
    
    if (cmd ==     EXCUTED_CMD_START_CM_EXER) {
        // 解析子命令
        NSNumber *subCmdNum = [CARingSDK analyCmdRespSubCmd:originData];
        if (!subCmdNum) {
            return ;
        }
        
        DebugNSLog(@"cm sub cmd 0x%X , result:%d", subCmdNum.intValue, isSucc);
        CAEXER_SUB_CMD subcmd = subCmdNum.unsignedCharValue; // 子命令
        NSString *cmdString = @"";
        if (subcmd == CAEX_STOP) {
            cmdString = _L2(L_END);
        }
        
        if (subcmd == CAEX_START) {
            cmdString = _L2(L_START);
        }
        if (subcmd == CAEX_PAUSE) {
            // 暂停
            cmdString = _L2(L_PAUSE);

        }
        
        if (subcmd == CAEX_CONTINUE) {
            cmdString = _L2(L_RESTORE);

        }
        
        if (isSucc) {
            NSString *msg = [NSString stringWithFormat:_L2(L_WK_EXCUTE_FMT), cmdString, @"succ" ];
            [LTPHud.Instance showHudLasting:1 Text:msg];
            //
        } else {
            //
            NSString *msg1 = [NSString stringWithFormat:_L2(L_WK_EXCUTE_FMT), _L2(L_END), @"failed" ];
            NSString *msg2 = [NSString stringWithFormat:_L2(L_CMD_EXCUTE_FMT_REASON),[CADeviceInfo descryOfErrorReason:reason], reason ];
            
            [self showAlertWarningWithTitle:@"Error" Msg:[msg1 stringByAppendingString:msg2] btnCancel:_L2(L_OK) Compelete:nil];

        }
        
      
    }
    
}

- (void)caBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging { 
    
}

- (void)caBleDeviceDidReadyForReadAndWrite:(nonnull CABLeService *)service { 
    
}

- (void)caBleDeviceInfo:(nonnull CADeviceInfo *)devInfo { 
    
}



- (void)caBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature { 
    
}

- (void)caBleDidConnectPeripheral:(nonnull CABLeService *)service { 
    
}

- (void)caBleDidDisconnectPeripheral:(nonnull CABLeService *)service { 
    
}

- (void)caBleFailConnectPeripheral:(nonnull CBPeripheral *)peripheral Error:(nonnull NSError *)error { 
    
}

- (void)srBleHistoryData:(nonnull CAHistoryData *)hisData IsComplete:(BOOL)isComplete {
    
}

- (void)caBleHistoryDataCount:(NSInteger)count { 
    
}

- (void)srBleHistoryDataTimeout { 
    
}

- (void)caBleHistorySr03Data:(nonnull CAHistoryDataSR03 *)hisData IsComplete:(BOOL)isComplete { 
    
}

- (void)caBleIsBinded:(BOOL)isBinded { 
    
}

- (void)caBleMeasureDuration:(NSInteger)seconds { 
    
}

- (void)caBleOEMAuthResult:(BOOL)authSucceddful { 
    
}

- (void)caBleRealtimeHRV:(nonnull NSNumber *)hrv BloodOxygen:(nonnull NSNumber *)bloodOxygen HeartRate:(nonnull NSNumber *)hr Status:(REALTIME_STATUS)status { 
    
}

- (void)caBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData { 
    
}




@end
